﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlServerCe;
using System.Linq;
using System.Text;
using VPSoftTestApplication.Entity;

namespace VPSoftTestApplication.DAL
{
    class DocumentHeaderControler:AbstractDocumentHeaderControler
    {
        public DocumentHeaderControler(string connectionString)
        {
            _connectionString = connectionString;
        }

        private List<DocumentHeader> ReadFromCommand (SqlCeCommand command)
        {
            List<DocumentHeader> documentHeaders = new List<DocumentHeader>();
            using (SqlCeDataReader dr = command.ExecuteReader())
            {
                int iid = dr.GetOrdinal("IID");
                int name = dr.GetOrdinal("Name");
                int documentCode = dr.GetOrdinal("DocumentCode");
                int pdaID = dr.GetOrdinal("PDAID");
                int iturIID = dr.GetOrdinal("IturIID");
                int pdaDate = dr.GetOrdinal("PDADate");
                int createDate = dr.GetOrdinal("CreateDate");
                int workerIID = dr.GetOrdinal("WorkerIID");
                int aprove = dr.GetOrdinal("Aprove");
                while (dr.Read())
                {
                    DocumentHeader documentHeader = new DocumentHeader();
                    documentHeader.IID = dr.GetGuid(iid);
                    documentHeader.Name = dr.GetString(name);
                    documentHeader.DocumentCode = dr.GetString(documentCode);
                    documentHeader.PDADate = dr.GetDateTime(pdaDate);
                    documentHeader.PDAID = dr.GetString(pdaID);
                    documentHeader.IturIID = dr.GetGuid(iturIID);
                    documentHeader.CreateDate = dr.GetDateTime(createDate);
                    documentHeader.WorkerIID = dr.GetGuid(workerIID);
                    documentHeader.Aprove = dr.GetBoolean(aprove);
                   documentHeaders.Add(documentHeader);

                }
                return documentHeaders;
            }
        }

        public override List<DocumentHeader> List()
        {
            using (SqlCeConnection connection = new SqlCeConnection(_connectionString))
            {
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }
                using (SqlCeCommand command = connection.CreateCommand())
                {
                    command.CommandText =
                        "SELECT IID, Name, DocumentCode, PDAID, IturIID, PDADate, CreateDate, WorkerIID, Aprove " +
                        "FROM DocumentHeader";
                    return ReadFromCommand(command);
                }
            }
        }
    }
}
